package com.mallbook.controller.servlet.front;

import com.mallbook.model.pojo.Category;
import com.mallbook.model.pojo.Goods;
import com.mallbook.model.service.CategoryService;
import com.mallbook.model.service.GoodsService;
import com.mallbook.model.service.UserService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * @Author 宋明松
 * @Version V1.0.0
 * @Date 2022-07-05
 */
@WebServlet("/goods")
public class GoodsServlet extends HttpServlet {
    private GoodsService goodsService = new GoodsService();
    private CategoryService categoryService = new CategoryService();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        InitBarUtils.getInitBar(req, resp); // 初始化导航栏
        String opr = req.getParameter("opr");
        switch (opr) {
            case "view":
                doView(req, resp);
                break;
            case "list":
                doList(req, resp);
                break;
        }


    }

    private void doList(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        InitBarUtils.getInitBar(req, resp); // 初始化导航栏
        String cid = req.getParameter("cid");
        List<Goods> goodsList=goodsService.getALLGoodsByCid(cid);
        req.setAttribute("goodsList",goodsList);

       Category category= categoryService.getCategoryById(Integer.parseInt(cid));
       req.setAttribute("category",category);

        List<Goods> hotGoods = goodsService.getHotGoods(8); // 热卖商品
        req.setAttribute("hotGoods", hotGoods);
        req.getRequestDispatcher("/WEB-INF/front/goods_list.jsp").forward(req, resp);
    }

    private void doView(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String gid = req.getParameter("id");
        Goods goods = goodsService.getGoodsById(Integer.parseInt(gid));
        req.setAttribute("goods", goods);
        List<Goods> hotGoods = goodsService.getHotGoods(4);
        req.setAttribute("hotGoods", hotGoods);
        req.getRequestDispatcher("/WEB-INF/front/goods_view.jsp").forward(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
